import { commonPageSizeOptions, showTotalInfo } from '@/common/constVariable';
import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { message, Space, Table } from 'antd';
import { Ref, useEffect, useMemo, useRef, useState } from 'react';
import { ContacterAPI } from '../common/type';
import { getPersonalColumns } from '../mconfig';
import { editContacterService, personalTableService } from '../services';
import { CustomerSearchForm } from './CustomerSearchForm';

export const CustomerModal: React.FC<ContacterAPI.IOwenCustomerModal> = ({
  onClose,
  curRes,
  reloadManage,
  checkRows,
}) => {
  const announceRef: Ref<IOneModalRef> = useRef(null); //弹框的ref
  const customerFixCl = 'customer-modal-';

  /* 关闭弹窗 */
  const onCloseModal = () => {
    if (announceRef) {
      if (announceRef.current) {
        if (announceRef.current.onModalCancel) {
          announceRef.current.onModalCancel();
        }
      }
    }
  };

  /**
   * 保存分页参数
   */
  const [pageSizeObj, setPageSizeObj] = useState<any>({
    order: 'desc',
    page: 1,
    rows: 10,
    sort: 'ownTime',
  });

  // 表格选择框
  const [checkedRowKeys, setCheckedRowKeys] = useState<string[]>([]);

  /* 获取columns方法 */
  const columns: Record<string, any>[] = useMemo(() => {
    return getPersonalColumns();
  }, []);

  const {
    getTableValues,
    personalTableData,
    personalTableLoading,
    manageTableParams,
  } = personalTableService(curRes);

  useEffect(() => {
    if (curRes && JSON.stringify(curRes) != '{}') {
      reloadTable(pageSizeObj);
    }
  }, [curRes]);

  // 分页页数 和数据条数改变
  const handlePaginationChange = (page: number, pageSize: number) => {
    let params = {
      ...pageSizeObj,
      page: page,
      rows: pageSize,
    };
    setPageSizeObj(params);
    // 获取用户数据
    getTableValues({ ...params, ...manageTableParams });
  };

  /**
   * 表格选中操作
   * @param selectedRowKeys
   * @param selectedRows
   * @param type
   */
  const tableChange = (
    selectedRowKeys: any,
    selectedRows: any,
    type?: string,
  ) => {
    if (type == 'rowClick') {
      let newIds: string[] = [selectedRowKeys];
      setCheckedRowKeys(newIds);
    } else {
      setCheckedRowKeys(selectedRowKeys);
    }
  };

  /**
   * 搜索,初始化
   * @param params
   */
  const reloadTable = (params: any) => {
    let payload: any = {
      ...pageSizeObj,
      ...params,
    };
    getTableValues(payload);
  };

  /**
   * 接口回调
   * @param res
   */
  const isOwenCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      onCloseModal();
      reloadManage();
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 引入编辑接口
   */
  const { editContacterLoading, editContacterRun } = editContacterService(
    isOwenCallback,
  );

  /**
   * 保存
   */
  const saveOnOk = () => {
    if (checkedRowKeys && checkedRowKeys?.length > 0) {
      let payload: any = {
        id: checkRows?.id,
        versionNum: checkRows?.versionNum,
        customerID: checkedRowKeys?.toString(),
      };
      editContacterRun(payload);
    } else {
      message.warning('请选择一位客户！');
    }
  };

  return (
    <>
      <OneModal
        open={true}
        ref={announceRef}
        title={'设置归属客户'}
        width={document.body.clientWidth * 0.55}
        onCancel={onClose}
        bodyStyle={{
          padding: '10px 1rem',
          maxHeight: document.body.clientHeight * 0.6,
        }}
        centered
        confirmLoading={editContacterLoading}
        onOk={saveOnOk}
      >
        <div className={customerFixCl + 'divBox'}>
          <div className={customerFixCl + 'tableRight-contentTitle'}>
            <CustomerSearchForm searchReloadTable={reloadTable} />
          </div>
          <div className={customerFixCl + 'tableRight-content'}>
            <div className={'list-table'}>
              <Table
                size="small"
                columns={columns}
                bordered
                loading={personalTableLoading}
                dataSource={personalTableData?.rows}
                scroll={{ x: 800, y: 'true' }}
                rowKey={(record: any) => {
                  return record?.id;
                }}
                pagination={{
                  showQuickJumper: true,
                  showSizeChanger: true,
                  pageSizeOptions: commonPageSizeOptions,
                  showTotal: showTotalInfo,
                  onChange: handlePaginationChange,
                  pageSize: pageSizeObj?.rows,
                  current: pageSizeObj?.page,
                  total: personalTableData?.total,
                }}
                rowSelection={{
                  type: 'radio',
                  selectedRowKeys: checkedRowKeys,
                  onChange: tableChange as any,
                }}
                onRow={(record: any) => {
                  return {
                    onClick: (event) => {
                      event.stopPropagation();
                      tableChange(record?.id, record, 'rowClick');
                    },
                  };
                }}
              />
            </div>
          </div>
        </div>
      </OneModal>
    </>
  );
};
